package com.mrkun.vueshop.script;

import com.mrkun.vueshop.mapper.FundInfoMapper;
import com.mrkun.vueshop.mapper.FundMapper;
import com.mrkun.vueshop.mapper.OrderInfoMapper;
import com.mrkun.vueshop.mapper.OrderMapper;
import com.mrkun.vueshop.model.Fund;
import com.mrkun.vueshop.model.FundInfo;
import com.mrkun.vueshop.model.Order;
import com.mrkun.vueshop.model.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author by yong
 * @date 2020/3/20
 */
@Service
@EnableTransactionManagement  // 启注解事务管理
public class GenerateData {
    @Autowired
    private FundMapper fundMapper;

    @Autowired
    private FundInfoMapper fundInfoMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Transactional(rollbackFor=Exception.class)
    public void insertData(String str){
        try{
            List<Fund> all = fundMapper.findAll("%%");
            for (Fund fund : all) {
                FundInfo fundInfo = new FundInfo();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar instance = Calendar.getInstance();

                Date date;
                if (str.isEmpty() || str == null){
                    date = new Date();
                }else {
                    date = sdf.parse(str);
                }
                fundInfo.setEveryDate(sdf.format(date));
                fundInfo.setFundId(fund.getId());
                //判断今天是否产生净值
                if(fundInfoMapper.findToday(sdf.format(date), fund.getId()) == null) {
                    instance.setTime(date);
                    instance.add(Calendar.DAY_OF_MONTH,-1);
                    date = instance.getTime();
                    //判断昨天是否产生单位净值
                    FundInfo yesterday = fundInfoMapper.findToday(sdf.format(date), fund.getId());
                    if (yesterday == null){
                        //新发布的基金不产生收入
                        //随机产生单位净值 [0.5,1.5)
                        Double today = Math.random()+0.5;
                        BigDecimal todyBig = new BigDecimal(today.toString()).setScale(4, BigDecimal.ROUND_HALF_UP);
                        fundInfo.setNetAssetValue(todyBig);
                        fundInfo.setIncreases(new BigDecimal(0.0));
                        fundInfoMapper.addFundInfo(fundInfo);
                    }else{
                        //获取到昨天的单位净值
                        BigDecimal yesterdayBig = yesterday.getNetAssetValue();
                        //随机产生今天的增加净值 ,取小数点后四位
                        Double avs = Math.signum(Math.random() - 0.15) * (Math.random() / 30);
                        BigDecimal bigDecimal = new BigDecimal((avs).toString()).setScale(4, BigDecimal.ROUND_HALF_UP);
                        //今天的单位净值= 昨天的单位净值+增加净值
                        BigDecimal todayBig = yesterdayBig.add(bigDecimal);
                        fundInfo.setNetAssetValue(todayBig);
                        fundInfo.setIncreases(bigDecimal.divide(yesterdayBig,4,BigDecimal.ROUND_HALF_UP));
                        fundInfoMapper.addFundInfo(fundInfo);
                    }
                }
            }
        }catch(Exception e){
            throw new RuntimeException("回滚");
        }
    }

    /**
     * 净值发生变化，所有的订单就要更新，根据什么来确定更新的依据呢，分两步操作，
     * 先判断今天有没有收益，有就不操作，没有就
     * @param strDate
     */

    @Transactional(rollbackFor = Exception.class)
    public void userIncome(String strDate){
        try{
            //获取到订单表里所有没有结束的订单
            List<Order> allNotEnd = orderMapper.findAllNotEnd();
            for (Order order : allNotEnd){
                OrderInfo orderInfo = orderInfoMapper.findByDateAndOrderId(strDate, order.getId());
                if (orderInfo == null){
                    BigDecimal money = order.getMoney();
                    BigDecimal increases = fundInfoMapper.getIncrease(order.getFundId(),strDate);
                    //今天收益
                    BigDecimal todayIncome = money.multiply(increases).setScale(2,BigDecimal.ROUND_HALF_UP);
                    //收益总和
                    order.setTotalIncome(order.getTotalIncome().add(todayIncome));
                    //总金额=昨日金额+今日收益
                    order.setMoney(order.getMoney().add(todayIncome));
                    orderMapper.updateMoneyAndIncome(order.getMoney(),order.getTotalIncome(),order.getId());
                    OrderInfo info = new OrderInfo();
                    info.setDate(strDate);
                    info.setOrderId(order.getId());
                    info.setTotalMoney(order.getMoney());
                    info.setIncome(todayIncome);
                    orderInfoMapper.addOrderInfo(info);
                }
            }
        }catch(Exception e){
            throw new RuntimeException("回滚");
        }
    }
}
